package com.kui.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kui.entity.User;
import com.kui.service.UserService;
import com.kui.util.HashUtil;

public class LoginServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		
		if(name != null && password != null){
			UserService us = new UserService();
			try {
				password=HashUtil.getHashString(password);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			User user = us.findByNameAndPassword(name,password);
			if(user != null){
				HttpSession session = request.getSession();
				session.setAttribute("user", user);
				out.print("10000");
			}else{
				out.print("10002");
			}
		}else{
			out.print("10001");
		}
		
		
		out.flush();
		out.close();
	}

}
